﻿using Aker.DevTeam;
using DevTeam;
using Extensions;
using System;
using System.Data;
using System.Drawing;

namespace Aker.Hammadde
{
    public partial class TopluMetrajGuncelleme : XForm
    {
        public TopluMetrajGuncelleme()
        {
            InitializeComponent();
        }

        DataTable dt;
        private void TopluMetrajGuncelleme_Load(object sender, EventArgs e)
        {
            Data.TAM.ShelfTableAdapter.Fill(Data.DB.Shelf);
            dt = Data.DM.ExecuteDataTable("GetHammaddeTopluGuncelleme");
            gv.Init(dt);
            gv.MakeReadOnly("KG", "Adet", "ShelfId", "Lot");
            gv.SetCaptions("ShelfId:Raf");
            gv.Columns["ShelfId"].ColumnEdit = Utility.GetGLESablon(Data.DB.Shelf, "Name", "ShelfId");
            gv.CellValueChanged += gv_CellValueChanged;
            gv.RowStyle += gv_RowStyle;
            gv.RowCellStyle += gv_RowCellStyle;
            gv.EnableComplexFiltering("Hammadde");
            gv.OptionsView.ShowViewCaption = false;
            gv.BestFitColumns();
        }

        void gv_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.RowHandle > -1 && "KG Adet ShelfId Lot".Contains(e.Column.FieldName))
                e.Appearance.BackColor = Color.LightYellow;
        }

        void gv_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (e.RowHandle > -1)
                if ((bool)gv.GetRowCellValue(e.RowHandle, "Changed"))
                {
                    e.Appearance.BackColor = Color.LightSalmon;
                }
        }


        void gv_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            gv.CellValueChanged -= gv_CellValueChanged;
            gv.SetRowCellValue(e.RowHandle, "Changed", true);
            gv.CellValueChanged += gv_CellValueChanged;
        }

        private void btnKaydet_Click(object sender, EventArgs e)
        {
            DataTable copy = dt.Copy();
            for (int i = copy.Columns.Count - 1; i > 1; i--)
                if (!"IplikId ElyafId KG ShelfId Adet Lot".Contains(copy.Columns[i].ColumnName))
                    copy.Columns.Remove(copy.Columns[i]);

            string changes = copy.SerializeChanges();

            if (changes.Replace("<MyData />", "") != "")
            {
                foreach (DataRow dr in dt.Rows)
                    if ((bool)dr["Changed"])
                        dr["Changed"] = false;

                Data.DM.ExecuteNonQuery("InsHammaddeTopluGuncelle", changes);
                dt.AcceptChanges();

                ShowInfo("Değişiklikler kaydedildi.");
            }
            else
                ShowError("Değişiklik yok !");

        }
    }
}
